package cn.xspace.wnx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.CommonItemBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.ErrorCode;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.HeadShowUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.RoundAngleImageView;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;
import com.xspace.android.xafcommon.view.dialog.PopupWindowHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.library.util.Tools;
import cn.xspace.wnx.R;
import cn.xspace.wnx.db.ChatRecordDao;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.wnx.db.MyNewFriendDao;
import cn.xspace.wnx.entity.NewFriendBean;
import cn.xspace.wnx.util.Navigator;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/27.
 */

public class PersonCardActivity extends BaseActivity {

    private static final String TAG = PersonCardActivity.class.getSimpleName();
    public static final String FRIEND_ID = "FRIEND_ID";
    public static final String ADD_FRIEND = "ADD_FRIEND";
    public static final String ADD_FRIEND_DESC = "ADD_FRIEND_DESC";

    private TitleBar mTitlebar;
    private RelativeLayout layoutUserInfo;
    private LinearLayout layoutUserInfoDown; //个人信息下半部分
    private ImageView headImg;
    private ImageView sexImg;
    private TextView userNameTxt;
    private TextView areaTxt;
    private TextView personWordTxt;
    private TextView phoneTxt;
    private TextView emailTxt;
    private TextView orgTxt;
    private TextView deptTxt;
    private TextView dutyTxt;
    private RelativeLayout sendMsgRelative;
    private TextView tvPersonCardBottom;

    private RelativeLayout RlVerification; //好友验证信息
    private TextView reqDescTxt;
    private RelativeLayout deptRelative;
    private RelativeLayout personPhone;
    private RelativeLayout personEmail;

    private RelativeLayout rlNetWorkInfo;
    private Button btReload;

    private String searchId = "";
    private String searchPhone = "";
    private OrgDeptUserBean mBean;

    private boolean isAddFriend = false; //是否是好友申请信息
    private String addFriendDesc = "";

    private boolean isFarmer; //是否农民


    private ArrayList<String> actionMode;


    @Override
    protected void getIntentData() {
        super.getIntentData();
        searchId = getIntent().getStringExtra(FRIEND_ID);
        LogUtil.e(TAG, "wubaojie>>>" + "getIntentData: " + searchId + "\tuser_id : " + MyInfoUtil.getMyUserid(this));
        isAddFriend = getIntent().getBooleanExtra(ADD_FRIEND, false);
        if (isAddFriend) {
            addFriendDesc = getIntent().getStringExtra(ADD_FRIEND_DESC);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_user_card);
    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        mTitlebar = (TitleBar) findViewById(R.id.title_bar);
        layoutUserInfo = (RelativeLayout) findViewById(R.id.layout_user_info);
        layoutUserInfo.setVisibility(View.INVISIBLE);

        RlVerification = (RelativeLayout) findViewById(R.id.relative_verification);
        reqDescTxt = (TextView) findViewById(R.id.txt_req_desc);

        headImg = (RoundAngleImageView) findViewById(R.id.img_head);
        userNameTxt = (TextView) findViewById(R.id.txt_user_name);
        sexImg = (ImageView) findViewById(R.id.img_sex);

        areaTxt = (TextView) findViewById(R.id.txt_area);
        personWordTxt = (TextView) findViewById(R.id.txt_person_word);
        phoneTxt = (TextView) findViewById(R.id.txt_phone);
        emailTxt = (TextView) findViewById(R.id.txt_email);

        layoutUserInfoDown = (LinearLayout) findViewById(R.id.layout_user_info_down);
        orgTxt = (TextView) findViewById(R.id.txt_org_name);
        deptTxt = (TextView) findViewById(R.id.txt_dept_name);
        deptRelative = (RelativeLayout) findViewById(R.id.relative_org_name);
        personPhone = (RelativeLayout) findViewById(R.id.rl_person_phone);
        personEmail = (RelativeLayout) findViewById(R.id.rl_person_email);
        dutyTxt = (TextView) findViewById(R.id.txt_duty);
        // 底部发送消息按钮
        sendMsgRelative = (RelativeLayout) findViewById(R.id.relativew_send_msg);
        tvPersonCardBottom = (TextView) findViewById(R.id.tv_person_card_bottom);
        if (TextUtils.equals(searchId, MyInfoUtil.getMyUserid(this))) {
            sendMsgRelative.setVisibility(View.GONE);
        }
        // 网络状态访问出错面板
        rlNetWorkInfo = (RelativeLayout) findViewById(R.id.layout_net_work_info);
        btReload = (Button) findViewById(R.id.bt_net_work_reload);
    }

    @Override
    protected void initData() {
        if ("1".equals(MyInfoUtil.getIsFarmer())) {
            isFarmer = true;
        }
        searchUserInfo();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mTitlebar.setTitle(getResources().getString(R.string.user_info));
        mTitlebar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitlebar.setRightLayoutVisibility(View.GONE);
        sendMsgRelative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mBean != null) {
                    if (!isFarmer) { //不是农民才有这些操作
                        if (notFriendAndColleague(mBean)) { //不是好友并且不是同事,并且不是申请好友验证
                            Intent intent = new Intent(mContext, AddFriendInfoActivity.class);
                            intent.putExtra("friend_id", searchId);
                            startActivity(intent);
                            return;
                        } else if (addFriend(mBean)) { //申请好友验证
                            NewFriendBean bean = new NewFriendBean();
                            bean.user_id = searchId;
                            bean.user_logo = mBean.user_logo;
                            bean.user_name = mBean.user_name;
                            requestConfirm(bean);
                            return;
                        }
                    }
                    Bundle dataBundle = new Bundle();
                    dataBundle.putString(BldNavigation.SENDER_ID, mBean.user_id);
                    dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_SINGLE.toNumber());
                    dataBundle.putString(BldNavigation.CHAT_NAME, mBean.user_name);
                    dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, mBean.user_logo);
                    dataBundle.putString(BldNavigation.CHAT_SENDER_SEX, mBean.user_sex);
                    Navigator.startChatActivity(mContext, dataBundle);
                }
            }
        });
        deptRelative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBean != null && !TextUtils.isEmpty(mBean.org_id)) { //防止服务器返回的数据为空
                    //从个人名片进入时传递要该人的Id
//                    Bundle dataBundle = new Bundle();
//                    dataBundle.putString(RequestConstant.KEY_ORG_ID, mBean.org_id);
//                    dataBundle.putString(RequestConstant.KEY_SEARCH_ID, searchId);
//                    dataBundle.putString(RequestConstant.KEY_SEARCH_PHONE, searchPhone);
//                    Navigator.startOrgInfoActivity(mContext, dataBundle);
                    Navigator.startOrgInfoActivity(mContext, mBean.org_id);
                }
            }
        });
        personPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBean != null && !TextUtils.isEmpty(mBean.user_mobile)) {
                    actionMode = new ArrayList<>();
                    actionMode.add(mBean.user_mobile);
                    actionMode.add(Tools.Action.CALL_PHONE);
                    actionMode.add(Tools.Action.SEND_MESSAGE);
                    actionMode.add(Tools.Action.CLIP_NUMBER);
                    actionMode.add(Tools.Action.CANCEL);
                    Tools.showPhoneOrEmailDialog(mContext, actionMode);
                }
            }
        });
        personEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBean != null && !TextUtils.isEmpty(mBean.user_email)) {
                    actionMode = new ArrayList<>();
                    actionMode.add(mBean.user_email);
                    actionMode.add(Tools.Action.SEND_EMAIL);
                    actionMode.add(Tools.Action.CLIP_EMAIL);
                    actionMode.add(Tools.Action.CANCEL);
                    Tools.showPhoneOrEmailDialog(mContext, actionMode);
                }
            }
        });
        btReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchUserInfo();
            }
        });

    }

    /**
     * 同意好友申请
     *
     * @param bean
     */
    private void requestConfirm(final NewFriendBean bean) {
        showWaitDialog();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", MyInfoUtil.getMyUserid(mContext));
        requestMap.put("friend_id", bean.user_id);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.ADD_FRIEND_RESPONSE, requestMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        bean.add_status = 1;
                        T.showShort(mContext, "添加好友成功");
                        MyNewFriendDao.getInstance().updateFriendStatus(bean);
                        afterAddFriend(bean);
                    }
                }));
    }

    /**
     * 成为好友后的界面修改
     *
     * @param bean
     */
    private void afterAddFriend(NewFriendBean bean) {
        mBean.isFriend = true;
        isAddFriend = false;
        tvPersonCardBottom.setText(R.string.msg_send);
        showTitleRight();
        //发送到新的好友界面，刷新界面
        Map<String, Object> inParam = new HashMap<>();
        inParam.put(EventBusConstant.TYPE, EventBusConstant.NEW_FRIEND_PUSH);
        inParam.put(EventBusConstant.ACTION_KEY, EventBusConstant.NEW_FRIEND_FINISH);
        inParam.put(EventBusConstant.NEW_FRIEND_PUSH_BEAN, bean);
        EventBus.getDefault().post(inParam);
    }

    private void searchUserInfo() {
        rlNetWorkInfo.setVisibility(View.GONE);
        showWaitDialog();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", MyInfoUtil.getMyUserid(mContext));
        requestMap.put("friend_id", searchId);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.QUERY_USER_BUSINESS_CARD, requestMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, OrgDeptUserBean>() {

                    @Override
                    public OrgDeptUserBean call(BaseReturnBean baseReturnBean) {

                        if (!ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                            return null;
                        }
                        OrgDeptUserBean userBean = new OrgDeptUserBean();
                        try {
                            JSONObject dataJson = new JSONObject(baseReturnBean.data);
                            userBean.user_id = dataJson.optString("user_id");
                            userBean.user_name = dataJson.optString("user_name");
                            userBean.user_logo = dataJson.optString("user_logo");
                            userBean.user_mobile = dataJson.optString("user_mobile");
                            userBean.user_email = dataJson.optString("user_email");
                            userBean.user_desc = dataJson.optString("user_desc");
                            userBean.user_sex = dataJson.optString("user_sex");
                            userBean.user_areaname = dataJson.optString("user_areaname");
                            userBean.dept_id = dataJson.optString("user_deptid");
                            userBean.dept_name = dataJson.optString("user_deptname");
                            userBean.org_id = dataJson.optString("user_orgid");
                            userBean.org_name = dataJson.optString("user_orgname");
                            String isColleague = dataJson.optString("iscolleague");
                            if ("1".equals(isColleague)) {
                                userBean.isColleague = true;
                            }
                            String isFriend = dataJson.optString("isfriend");
                            if ("1".equals(isFriend)) {
                                userBean.isFriend = true;
                            }
                            JSONArray postArray = dataJson.getJSONArray("postList");
                            List<OrgDeptUserBean.Post> postList = new ArrayList<OrgDeptUserBean.Post>();
                            int size = postArray.length();
                            for (int i = 0; i < size; i++) {
                                OrgDeptUserBean.Post post = userBean.new Post();
                                JSONObject postJson = postArray.getJSONObject(i);
                                post.post_id = postJson.optString("post_id");
                                post.post_name = postJson.optString("post_name");
                                postList.add(post);
                            }
                            userBean.postList = postList;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return userBean;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<OrgDeptUserBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        T.showShort(mContext, e.getMessage());
                        hideWaitDialog();
                        dealNetWorkError();
                    }

                    @Override
                    public void onNext(OrgDeptUserBean orgDeptUserBean) {
                        hideWaitDialog();
                        if (orgDeptUserBean == null) {
                            sendMsgRelative.setEnabled(false);
                            T.show(mContext, getResources().getString(R.string.request_data_error), Toast.LENGTH_SHORT);
                            return;
                        }
                        mBean = orgDeptUserBean;
                        LogUtil.d(orgDeptUserBean.toString());
                        fillView(orgDeptUserBean);
                    }

                }));

    }

    private void dealNetWorkError() {
        rlNetWorkInfo.setVisibility(View.VISIBLE);
    }


    private void fillView(OrgDeptUserBean orgDeptUserBean) {
        layoutUserInfo.setVisibility(View.VISIBLE);
        mTitlebar.setRightLayoutVisibility(View.GONE);
        if (!isFarmer) { //不是农民才有好友关系
            if (notFriendAndColleague(orgDeptUserBean)) { //不是同事并且不是朋友,并且不是来申请好友
                layoutUserInfoDown.setVisibility(View.GONE);
                personEmail.setVisibility(View.GONE);
                tvPersonCardBottom.setText(R.string.add_friend);
            } else if (addFriend(orgDeptUserBean)) { //如果是好友申请,则显示好友验证详情
                RlVerification.setVisibility(View.VISIBLE);
                reqDescTxt.setText(addFriendDesc);
                tvPersonCardBottom.setText(R.string.confirm);
            } else if (isFriend(orgDeptUserBean)) { //真的是好友了
                showTitleRight();
            }
        }
        HeadShowUtil.headShow(mContext, orgDeptUserBean.user_logo, orgDeptUserBean.user_sex, headImg, HeadShowUtil
                .HeadType.UserLogo);
        if (!TextUtils.isEmpty(orgDeptUserBean.user_sex)) {
            if (OrgDeptUserBean.Sex.Man.getTxt().equals(orgDeptUserBean.user_sex)) {
                sexImg.setImageResource(R.drawable.icon_man);
            } else if (OrgDeptUserBean.Sex.Woman.getTxt().equals(orgDeptUserBean.user_sex)) {
                sexImg.setImageResource(R.drawable.icon_woman);
            }
        }
        userNameTxt.setText(orgDeptUserBean.user_name);
        areaTxt.setText(orgDeptUserBean.user_areaname);
        personWordTxt.setText(TextUtils.isEmpty(orgDeptUserBean.user_desc) ? getResources().getString(R.string
                .person_word_default) : orgDeptUserBean.user_desc);
        phoneTxt.setText(orgDeptUserBean.user_mobile);
        emailTxt.setText(TextUtils.isEmpty(orgDeptUserBean.user_email) ? getResources().getString(R.string
                .msg_default) : orgDeptUserBean.user_email);

        orgTxt.setText(orgDeptUserBean.org_name);
        deptTxt.setText(orgDeptUserBean.dept_name);
        String duty = "";
        for (OrgDeptUserBean.Post post : orgDeptUserBean.postList) {
            duty += post.post_name;
            duty += " ";
        }
        dutyTxt.setText(TextUtils.isEmpty(duty) ? getResources().getString(R.string.msg_default) : duty);
    }

    /**
     * 显示右上角popupWindow
     */
    private void showTitleRight() {
        mTitlebar.setRightLayoutVisibility(View.VISIBLE);
        mTitlebar.setRightImageResource(R.drawable.icon_function_more);
        mTitlebar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMorePopup(mTitlebar.getRightImage());
            }
        });
    }

    /**
     * 显示更多弹窗
     *
     * @param v
     */
    private void showMorePopup(View v) {
        PopupWindowHelper helper = PopupWindowHelper.newInstance(mContext);
        ArrayList<CommonItemBean> list = new ArrayList<>();
        list.add(new CommonItemBean(getString(R.string.delete_friend), 1));
        helper.setDataList(list)
                .setListener(new PopupWindowHelper.IPopupClickListener() {
                    @Override
                    public void onItemClick(View view, CommonItemBean bean, int position) {
                        if (bean.tag == 1) {
                            showDeleteDialog();
                        }
                    }
                }).showPopup(v);
    }

    /**
     * 显示删除对话框
     */
    private void showDeleteDialog() {
        DialogHelp.getConfirmDialog(mContext,
                String.format(ResourceUtils.getString(R.string.delete_friend_info), mBean.user_name),
                ResourceUtils.getString(R.string.delete_friend_info2),
                ResourceUtils.getString(R.string.cancel),
                ResourceUtils.getString(R.string.button_ok),
                null, new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        deleteFriend();
                    }
                }).show();
    }

    /**
     * 删除好友
     * 在好友列表中删除:删除后,需要通知好友列表刷新
     * 在聊天信息查看名片时删除:需要通知聊天界面关闭
     */
    private void deleteFriend() {
        showWaitDialog();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", MyInfoUtil.getMyUserid(mContext));
        requestMap.put("friend_id", mBean.user_id);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.DEL_FRIENDS, requestMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        T.showShort(mContext, "删除好友成功");
                        dealDeleteSuccess();

                    }
                }));
    }

    /**
     * 处理删除好友成功后的事件
     */
    private void dealDeleteSuccess() {
//        mBean.isFriend = false;
//        fillView(mBean);
        //清空数据和信息,发送事件到名片页面,聊天页面,消息列表,我的好友页面
        ChatRecordDao.getInstance().getIChatRecordOperation().clearChatRecord(mBean.user_id,
                MsgType.CHAT_SINGLE.toNumber())
                .subscribeOn(Schedulers.io())
                .doOnNext(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        MessageRecordDao.getInstance().deleteSingleChat(mBean.user_id);
                    }
                })
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        Map<String, Object> datamap = new HashMap<String, Object>();
                        datamap.put(EventBusConstant.TYPE, EventBusConstant.DELETE_FRIEND_PUSH);
                        datamap.put(EventBusConstant.ACTION_KEY, EventBusConstant.DELETE_FRIEND_FINISH);
                        datamap.put(EventBusConstant.ACTION_VALUE, mBean.user_id);
                        EventBus.getDefault().post(datamap);
                        finish();
                    }
                });
//        //发送到我的好友列表,刷新数据
//        Map<String, Object> map = new HashMap<>();
//        map.put(EventBusConstant.TYPE, EventBusConstant.NEW_FRIEND_PUSH);
//        map.put(EventBusConstant.ACTION_KEY, EventBusConstant.DELETE_FRIEND_FINISH);
//        EventBus.getDefault().post(map);
    }

    /**
     * 不是好友并且不是同事,并且不是申请来加好友
     *
     * @param orgDeptUserBean
     * @return
     */
    private boolean notFriendAndColleague(OrgDeptUserBean orgDeptUserBean) {
        return !orgDeptUserBean.isColleague && !orgDeptUserBean.isFriend && !isAddFriend;
    }

    /**
     * 不是好友并且不是同事,申请来加好友
     *
     * @param orgDeptUserBean
     * @return
     */
    private boolean addFriend(OrgDeptUserBean orgDeptUserBean) {
        return !orgDeptUserBean.isColleague && !orgDeptUserBean.isFriend && isAddFriend;
    }

    /**
     * 是好友关系
     *
     * @param orgDeptUserBean
     * @return
     */
    private boolean isFriend(OrgDeptUserBean orgDeptUserBean) {
        return !orgDeptUserBean.isColleague && orgDeptUserBean.isFriend;
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        if (EventBusConstant.DELETE_FRIEND_PUSH.equals(inParam.get(EventBusConstant.TYPE))) {
            if (EventBusConstant.DELETE_FRIEND_FINISH.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                //好友关系解除,刷新信息页面
                if (mBean.user_id.equals(inParam.get(EventBusConstant.ACTION_VALUE))) {
                    mBean.isFriend = false;
                    fillView(mBean);
                }
            }
        }
    }
}
